package com.airforce.controller;

import com.airforce.model.uploadfile;
import com.airforce.utils.ResultCode;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping(value = "upload")
public class upload {


    /**
     * 图片上传
     * @param file
     * @return
     * @throws IOException
     * @throws ServletException
     */
    @PostMapping("img")
    public Object imgupload( @RequestParam MultipartFile file) throws IOException, ServletException {

        uploadfile uploadfile=new uploadfile();
        if (null != file) {
            String myFileName = file.getOriginalFilename();// 文件原名称
            System.out.println("获取文件名为:"+myFileName);

//          String path="d:/file/award/";本地配置
            String path="/opt/imgfile/"; //生产配置
            File fileDir=new File(path);
            if (!fileDir.exists()) { //如果不存在 则创建
                fileDir.mkdirs();
            }
            String pat=path+myFileName;  //要生成文件的路径+文件名
            File localFile = new File(pat);
            try {
                //将上传文件写入指定文件
                file.transferTo(localFile);
                uploadfile.setFilename(myFileName);
                uploadfile.setPath("http://ty108.com/dazhuanpan/img/"+myFileName);

            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            System.out.println("文件为空");
        }


        return ResultCode.SUCCESS.result(uploadfile);
    }


}
